class GameOver extends Spirit {
  constructor() {
    super('img/gameover.png')
    this.scale(0.5)
    this.blink = 0

    this.label = new Label('提示: 按 R 返回开始界面')
    this.label.color = '#FFE8E8'
    this.label.x = 110
    this.label.y = 320

  }

  draw(context) {
    if (this.blink < 30) {
      super.draw(context)
      this.label.draw(context)
    }
    if (this.blink > 60) {
      this.blink = 0
    }

    this.blink++
  }
}


class SceneMian extends Scene {
  constructor(game) {
    super(game)
    this.setup()
  }

  setup() {
    // add element
    this.addBg()
    this.addEnemies()
    this.addPlayer()
    this.addGameOver()
    // events
    this.bindEvent()
  }

  bindEvent() {
    this.game.registerAction('r', (state) => {
      if (state == 'up') {
        if (this.game.over) {
          const scene_start = new SceneStart(this.game)
          this.game.replaceScene(scene_start)
        }
      }
    })
  }

  update() {
    if (this.game.over) {
      return
    }
    super.update()
  }

  draw() {
    super.draw()
    if (this.game.over) {
      this.over.draw(this.game.context)
    }
  }

  addBg() {
    this.bg = new Background()
    this.add(this.bg)
  }

  addGameOver() {
    this.over = new GameOver()
    this.over.x = (this.game.canvas.width - this.over.w) / 2
    this.over.y = 250
  }

  addPlayer() {
    this.player = new Player()
    this.player.scale(0.6)
    this.player.x = (game.canvas.width - this.player.w) / 2
    this.player.y = 400

    this.game.registerAction('a', (state) => {
      console.log(state);
      this.player.moveLeft()
    })

    this.game.registerAction('d', () => {
      this.player.moveRight()
    })

    this.game.registerAction('w', () => {
      this.player.moveUp()
    })

    this.game.registerAction('s', () => {
      this.player.moveDown()
    })

    this.game.registerAction(' ', () => {
      this.player.fire()
    })

    this.add(this.player)
  }

  addEnemies() {
    this.enemies = []
    for (let i = 0; i < 20; i++) {
      let x = utils.random(0, 350)
      let y = utils.random(-3000, 200)
      const e = new Enemy(x, y)
      this.enemies.push(e)
      this.add(e)
    }
  }

  removeEnemy(enemy) {
    let index = this.enemies.indexOf(enemy)
    if (index > -1) {
      this.enemies.splice(index, 1)
    }
    this.remove(enemy)
  }
}